<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{Douyin, User as Users, Car, AgentArea, Promo, MoneyLog, Region, Compent, Product, Coupon, OrderProduct, Order, Pkey, Agent, Payment, Wechat, Riderlist, RiderStreet, IntergralLog, Message};
use think\Facade\Config as Configs;
use EasyWeChat\Factory;
use think\Validate;
use think\Db;
use think\facade\Log;

class User extends Base
{

    //订单评价
    public function compent()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'orderid' => 'require',
                'star' => 'require',
                'text' => 'require',
            ], [
                'orderid.require' => '订单不能为空',
                'star.require' => '星级不能为空',
                'text.require' => '评价内容不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!empty($data['images'])) {
                $images = json_decode($data['images'] ?? '', true) ?? [];
                if (is_array($images) && count($images) > 0) {
                    $data['images'] = json_encode($images, true);
                } else {
                    $data['images'] = '';
                }
            } else {
                $data['images'] = '';
            }
            $order = (new Order())->where(['status' => 4, 'id' => $data['orderid'], 'ispj' => 1, 'user_id' => $this->request->user_id])->find();
            if (empty($order)) {
                $this->result([], 1, '订单不可评价或已评价');
            }
            $data['user_id'] = $this->request->user_id;
            Db::startTrans();
            try {
                (new Order())->where('id', $order['id'])->update(['ispj' => 2]);
                (new Compent())->allowfield(true)->save($data);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败');
            }
            $this->result([], 0, '操作成功');
        }
    }

    public function dylogin()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'code' => 'require',
            'user' => 'require',
        ], [
            'code.require' => '抖音授权码不能为空',
            'user.require' => '抖音个人信息不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $time = 7 * 86400;
        try {
            $res = (new Douyin())->session($data['code']);
        } catch (\Exception $e) {
            $this->result([], 1, '获取信息错误,请重试');
        }
        if (empty($res['session_key']) || empty($res['openid'])) {
            $this->result([], 1, '登录失败,请重试');
        }
        $unique = 'session_key' . $res['openid'];
        Redis::setex($unique, 3 * 86400, $res['session_key']);
        $save = [
            'type' => 2,
            'session_key' => $res['session_key'],
            'openid' => $res['openid'],
            'dyopenid' => $res['openid'],
            'gender' => $data['user']['gender'] ?? 0,
            'province' =>  $data['user']['province'] ?? '',
            'city' =>  $data['user']['city'] ?? '',
            'avatarUrl' =>  $data['user']['avatarUrl'] ?? '',
            'country' =>  $data['user']['country'] ?? '',
            'nickName' =>  preg_replace('/[\xf0-\xf7].{3}/', '',  $data['user']['nickName'] ?? ''),
        ];
        if (empty($save['nickName'])) {
            $save['nickName'] = '抖音用户';
        }
        $model = new Users();
        // 判断用户是否已经注册
        $user = $model->where(['openid' => $save['openid'], 'type' => 2])->find();
        $savetime = !empty($user['created']) ? $user['created'] : date('Y-m-d H:i:s');
        if (!empty($data['puser']) && empty($user['pid']) && $savetime >= date('Y-m-d H:i:s', time() - 5 * 3600)) {
            $save['pid'] = $model->where('code', $data['puser'])->value('id') ?? 0;
        }
        if ($user) {
            $res2 = $model->allowfield(true)->save($save, ['id' => $user['id']]);
        } else {
            $save['code'] = recode($model);
            $res2 = $model->allowfield(true)->save($save);
            $user = $model->where(['openid' => $save['openid'], 'type' => 2])->find();
        }
        if ($res2 && !empty($user)) {
            $token = 'user_' . md5(time() . $user['code']);
            Redis::setex($token, $time, $user['id']);
            $this->result(['token' => $token], 0, '登录成功');
        }
        $this->result([], 1, '登录失败');
    }


    public function login()
    {
        // Redis::setex(123456, 86400, 1);
        // dump(1);
        $data = $this->request->post();
        $validate = new Validate([
            'code' => 'require',
            'iv' => 'require',
            'encryptedData' => 'require',
        ], [
            'code.require' => '微信授权码不能为空',
            'iv.require' => 'IV数据不能为空',
            'encryptedData.require' => 'encryptedData数据不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $model = new Users();
        $config = config('wechat.');
        $app = Factory::miniProgram($config);
        try {
            $res = $app->auth->session($data['code']);
        } catch (\Exception $e) {
            $this->result([], 1, '获取信息错误,请重试');
        }
        $time = $config['tokenExpireHours'];
        if (empty($res['session_key']) || empty($res['openid'])) {
            $this->result([], 1, '登录失败,请重试');
        }
        $unique = 'session_key' . $res['openid'];
        Redis::setex($unique, 3 * 86400, $res['session_key']);
        //判断用户是否已经注册
        $user = $model->where(['openid' =>  $res['openid'], 'type' => 1])->find();
        try {
            $decryptedData = $app->encryptor->decryptData($res['session_key'], $data['iv'], $data['encryptedData']);
        } catch (\Exception $e) {
            $this->result([], 1, $e->getMessage());
        }
        $save = [
            'session_key' => $res['session_key'],
            'openid' => $res['openid'],
            'wxopenid' => $res['openid'],
            'gender' => $decryptedData['gender'] ?? 0,
            'province' => $decryptedData['province'] ?? '',
            'city' => $decryptedData['city'] ?? '',
            'avatarUrl' => $decryptedData['avatarUrl'] ?? '',
            'country' => $decryptedData['country'] ?? '',
            'nickName' =>  preg_replace('/[\xf0-\xf7].{3}/', '', $decryptedData['nickName'] ?? ''),
        ];
        if (empty($save['nickName'])) {
            $save['nickName'] = '微信用户';
        }
        $savetime = !empty($user['created']) ? $user['created'] : date('Y-m-d H:i:s');
        if (!empty($data['puser']) && empty($user['pid']) && $savetime >= date('Y-m-d H:i:s', time() - 5 * 3600)) {
            $save['pid'] = $model->where('code', $data['puser'])->value('id') ?? 0;
        }
        if ($user) {
            $res2 = $model->allowfield(true)->save($save, ['id' => $user['id']]);
        } else {
            $save['code'] = recode($model);
            $res2 = $model->allowfield(true)->save($save);
            $user = $model->where('openid', $save['openid'])->find();
        }
        if ($res2 && !empty($user)) {
            $token = 'user_' . md5(time() . $user['code']);
            Redis::setex($token, $time, $user['id']);
            $this->result(['token' => $token], 0, '登录成功');
        }
        $this->result([], 1, '登录失败');
    }

    public function setmobile()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'code' => 'require',
            'iv' => 'require',
            'encryptedData' => 'require',
            'type' => 'require|in:1,2'
        ], [
            'code.require' => 'code不能为空',
            'iv.require' => 'iv不能为空',
            'encryptedData.require' => 'encryptedData不能为空',
            'type.require' => '类型不能为空',
            'type.in' => '类型参数不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $config = config('wechat.');
        $app = Factory::miniProgram($config);
        $user = (new Users())->where('id', $this->request->user_id)->find();
        if (!empty($user['mobile'])) {
            $this->result([], 1, '您已绑定手机号码,无需重复绑定');
        }
        if ($data['type'] == 1) {
            try {
                $res = $app->auth->session($data['code']);
            } catch (\Exception $e) {
                $this->result([], 1, '获取秘钥错误,请重试');
            }
        }
        if ($data['type'] == 2) {
            try {
                $res = (new Douyin())->session($data['code']);
            } catch (\Exception $e) {
                $this->result([], 1, '获取秘钥错误,请重试');
            }
        }
        if (empty($res['session_key']) || empty($res['openid'])) {
            $this->result([], 1, '操作失败,请重试');
        }
        //存session_key
        $unique = 'session_key' . $res['openid'];
        $frtimes = Redis::get($unique);
        Redis::setex($unique, 3 * 86400, $res['session_key']);
        if ($frtimes) {
            $res['session_key'] = $frtimes;
        }
        try {
            $decryptedData = $app->encryptor->decryptData($res['session_key'], $data['iv'], $data['encryptedData']);
        } catch (\Exception $e) {
            $this->result([], 1, '解析失败，请重试');
        }
        if (!empty($decryptedData['purePhoneNumber'])) {
            $data['mobile'] = $decryptedData['purePhoneNumber'];
            //查找手机号码是否已绑定
            $user = (new Users())->where('mobile', $data['mobile'])->find();
            if (!empty($user)) {
                $this->result([], 1, '授权失败,手机号码已被绑定');
            }
            $res = (new Users())->where('id', $this->request->user_id)->update(['mobile' => $data['mobile']]);
            if ($res) {
                $this->result(['mobile' => $data['mobile']], 0, '授权成功');
            }
        }
        $this->result([], 1, '授权失败');
    }

    public function mlogin()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'code' => 'require',
            'iv' => 'require',
            'encryptedData' => 'require',
            'type' => 'require|in:1,2'
        ], [
            'code.require' => 'code不能为空',
            'iv.require' => 'IV不能为空',
            'encryptedData.require' => 'encryptedData不能为空',
            'type.require' => '类型不能为空',
            'type.in' => '类型参数不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $config = config('wechat.');
        $time = $config['tokenExpireHours'];
        $app = Factory::miniProgram($config);
        if ($data['type'] == 1) {
            try {
                $res = $app->auth->session($data['code']);
            } catch (\Exception $e) {
                $this->result([], 1, '获取秘钥错误,请重试');
            }
        }
        if ($data['type'] == 2) {
            try {
                $res = (new Douyin())->session($data['code']);
            } catch (\Exception $e) {
                $this->result([], 1, '获取秘钥错误,请重试');
            }
        }
        if (empty($res['session_key']) || empty($res['openid'])) {
            $this->result([], 1, '操作失败,请重试');
        }
        //存session_key
        $unique = 'session_key' . $res['openid'];
        $frtimes = Redis::get($unique);
        Redis::setex($unique, 3 * 86400, $res['session_key']);
        if ($frtimes) {
            $res['session_key'] = $frtimes;
        }
        try {
            $decryptedData = $app->encryptor->decryptData($res['session_key'], $data['iv'], $data['encryptedData']);
        } catch (\Exception $e) {
            $this->result([], 1, '操作失败,请重试');
        }
        if (!empty($decryptedData['purePhoneNumber'])) {
            $data['mobile'] = $decryptedData['purePhoneNumber'];
            $user = (new Users())->where('mobile', $data['mobile'])->find();
            if (empty($user)) {
                $this->result([], 1, '请授权登陆绑定手机号后再尝试');
            }
            //更新openid用于登陆
            //更新openid用于登陆
            if ($user['type'] == 2 && empty($user['wxopenid'])) {
                (new Users())->where('id', $user['id'])->update(['wxopenid' => $res['openid']]);
            }
            if ($user['type'] == 1 && empty($user['dyopenid'])) {
                (new Users())->where('id', $user['id'])->update(['dyopenid' => $res['openid']]);
            }
            $token = 'user_' . md5(time() . $user['code']);
            Redis::setex($token, $time, $user['id']);
            $this->result(['token' => $token], 0, '登录成功');
        }
        $this->result([], 1, '登陆失败,请重试');
    }

    public function qrcode()
    {
        $user = $this->request->user;
        if ($user['type'] == 1) {
            $name = 'appcode' . $user['id'] . '.png';
            $qcode = url('/uploads/wechat/' . $name, '', '', true);
            $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/wechat/";
            if (!file_exists($path . $name)) {
                $config = config('wechat.');
                try {
                    if (!is_dir($path)) {
                        mkdir($path, 0777, true);
                    }
                    $app = Factory::miniProgram($config);
                    $rm = $app->app_code->getUnlimit('invite=' . $user['code'], [
                        'page'  => '',
                        'width' => 600,
                    ]);
                    if ($rm instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                        $rm->save($path, $name);
                    }
                } catch (\Exception $e) {
                    $this->result([], 1, $e->getMessage());
                }
            }
            $this->result($qcode, 0, '获取成功');
        } else {
            $name = 'appcode' . $user['id'] . '.png';
            $qcode = url('/uploads/zijie/' . $name, '', '', true);
            $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/zijie/";
            if (!file_exists($path . $name)) {
                try {
                    $res = (new Douyin())->qrcode('pages/index/index?scene=invite=' . $user['code']);
                    if ($res) {
                        file_put_contents($path . $name, $res);
                    }
                } catch (\Exception $e) {
                    $this->result([], 1, '获取信息错误,请重试');
                }
            }
            $this->result($qcode, 0, '获取成功');
        }
    }


    public function car()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'mobile' => 'require',
                'cards' => 'require',
                'model' => 'require|in:1,2,3',
                'is_default' => 'require|in:1,2',
                'type' => 'require|in:1,2',
                'color' => 'require'
            ], [
                'name.require' => '联系人姓名不能为空',
                'mobile.require' => '联系人电话不能为空',
                'cards.require' => '车牌号不能为空',
                'type.require' => '车牌类型不能为空',
                'type.in' => '车牌类型不正确',
                'model.require' => '车辆类型不能为空',
                'model.in' => '车辆类型不正确',
                'color.require' => '车辆颜色不能为空',
                'is_default.require' => '默认类型不能为空',
                'is_default.in' => '默认类型不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            // if (!isCarLicense($data['cards'])) {
            //     $this->result([], 1, '请输入正确的车牌号码');
            // }
            $data['user_id'] = $this->request->user_id;
            $model = new Car();
            Db::startTrans();
            try {
                (new Car())->where('user_id', $this->request->user_id)->update(['is_default' => 1]);
                if (!empty($data['id'])) {
                    $model->allowfield(true)->save($data, ['id' => $data['id']]);
                } else {
                    $model->allowfield(true)->save($data);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败');
            }
            $this->result([], 0, '操作成功');
        } else {
            $addressmodel = new Car();
            $result = $addressmodel->where('user_id', $this->request->user_id)->order('is_default desc')->field('user_id,created', true)->select();
            foreach ($result as $results) {
                $results['model_text'] = $results->model_text;
            }
            $this->result($result, 0, '操作成功');
        }
    }


    public function car_del()
    {
        $id = $this->request->post('id/d', 0);
        $addressmodel = new Car();
        $result = $addressmodel->where(['user_id' => $this->request->user_id, 'id' => $id])->delete();
        if ($result) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }

    public function keyend()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'key' => 'require'
        ], [
            'key.require' => '兑换码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        //查询兑换码是否存在
        $key = (new Pkey())->where(['code' => $data['key'], 'status' => 1, 'type' => 1])->find();
        if (empty($key)) {
            $this->result([], 1, '兑换码不正确或已使用(兑换码区分大小写)');
        }
        //兑换码存在查询活动是否还在继续
        $promo = (new Promo())->where(['id' => $key['promoid'], 'status' => 1, 'type' => 1])->find();
        if (empty($promo)) {
            $this->result([], 1, '兑换码已失效');
        }
        $coupons = [];
        $promo['coupon'] = json_decode($promo['coupon'], true) ?? [];
        foreach ($promo['coupon'] as $coupon) {
            $coupon['type'] = implode(',', $coupon['type']);
            $modelcount = count($coupon['carmodel']);
            $coupon['carmodel'] = implode(',', $coupon['carmodel']);
            $number = (int)$coupon['number'] ?? 1;
            for ($i = 0; $i < $number; $i++) {
                $coupons[] = [
                    'type' => 1,
                    'types' => 2,
                    'user_id' => $this->request->user_id,
                    'agentid' => $promo['agentid'],
                    'productid' => $coupon['type'],
                    'carmodel' => $coupon['carmodel'],
                    'modelcount' => $modelcount,
                    'number' => 1,
                    'status' => 1,
                    'endtime' => date('Y-m-d H:i:s', time() + 86400 * ($coupon['days'] ?? 10000)),
                    'promo' => $promo['id'],
                    'keyid' => $key['id']
                ];
            }
        }
        Db::startTrans();
        try {
            if (count($coupons) > 0) {
                (new Coupon())->allowfield(true)->saveAll($coupons);
            }
            // if ($this->request->user['level'] == 1) {
            //     (new Users())->where(['id' => $this->request->user_id])->update(['level' => 2]);
            // }
            // if ($promo['agentid'] > 0) {
            //     (new Agent())->MoneyEdit2($promo['agentid'], 2, $promo['money'], '使用兑换码', 0);
            // }
            (new Pkey())->where('id', $key['id'])->update(['status' => 2, 'user_id' => $this->request->user_id, 'ltime' => date('Y-m-d H:i:s')]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, $e->getMessage());
        }
        $this->result([], 0, '兑换成功,请前往卡券查看');
    }

    public function getcoupon()
    {
        $data = $this->request->get();
        $type =  $this->request->get('type/d', 0);
        if (!empty($type)) {
            $list = (new Coupon())
                ->where(['user_id' => $this->request->user_id, 'status' => 1])
                ->field('id,type,types,agentid,productid,carmodel,getmoney,system,money,status,endtime,text,number,created')
                ->order('id desc');
            $list = $list->where('types', $type);
            $list = $list->select();
        } else {
            $list = [];
            $list1 = (new Coupon())
                ->where(['user_id' => $this->request->user_id, 'status' => 1, 'types' => 1])
                ->field('id,type,types,agentid,productid,carmodel,getmoney,system,money,status,endtime,text,number,created')
                ->order('id desc')->select()->toArray();
            $list2 = (new Coupon())
                ->where(['user_id' => $this->request->user_id, 'status' => 1, 'types' => 2])
                ->group('type,types,agentid,productid,carmodel,endtime')
                ->field('id,type,types,agentid,productid,carmodel,getmoney,system,money,status,endtime,text,sum(number) as number,created')
                ->order('id desc')->select()->toArray();
            $list = array_merge($list1, $list2);
        }
        $total = 0;
        $agentid = 0;
        if (!empty($data['productid'])) {
            $data['productid'] = json_decode($data['productid'] ?? '', true);
            if (empty($data['productid'])) {
                $this->result([], 1, '规格数据错误');
            }
            foreach ($data['productid'] as $spec) {
                if (empty($spec['id'])  || empty($spec['number'])) {
                    continue;
                }
                //判断商品是否下架
                $product = (new Product())->where(['isdel' => 1, 'isshow' => 1, 'id' => $spec['id']])->find();
                if (empty($product)) {
                    continue;
                }
                if ($agentid == 0 && $agentid != $product['agentid']) {
                    $agentid = $product['agentid'] ?? 0;
                }
                $total += $product['price'] * $spec['number'];
            }
        }
        foreach ($list as $k => &$lists) {
            if ($lists['type'] == 1) {
                $lists['title'] = '平台满减券';
            }
            if ($lists['type'] == 2) {
                $lists['title'] = '区域满减券';
            }
            if ($lists['system'] == 4) {
                $lists['title'] = '新用户满减券';
            }
            $lists['text'] = '本券最终解释权为平台所有。';
            if ($lists['types'] == 2) {
                if ($lists['system'] == 3) {
                    if ($lists['getmoney'] == 0) {
                        $lists['title'] = '免费洗车卡';
                    } else {
                        $lists['title'] = $lists['getmoney'] . '元洗车卡';
                    }
                } elseif ($lists['system'] == 4) {
                    if ($lists['getmoney'] == 0) {
                        $lists['title'] = '新用户免费洗车卡';
                    } else {
                        $lists['title'] = '新用户' . (float)$lists['getmoney'] . '元起洗车卡';
                    }
                } elseif ($lists['system'] == 5) {
                    $lists['title'] = '平台洗车卡(套餐)';
                } else {
                    $lists['title'] = '平台洗车卡';
                }
                if ($lists['agentid'] == 0) {
                    $lists['title'] = $lists['title'];
                } else {
                    $title = (new Agent())->where('id', $lists['agentid'])->value('title') ?? '';
                    if (!empty($title)) {
                        $lists['title'] = $lists['title'] . '(' . $title . '可用)';
                    }
                }
                $typess = explode(',', $lists['productid']);
                $carmodel = explode(',', $lists['carmodel']);
                $lists['text'] = '';
                $text2 = '';
                $text = '';
                foreach ($carmodel as $k => $types) {
                    $type_texts = config()['config']['carmodel'][$types] ?? '';
                    if (!empty($text2) && empty($carmodel[$k + 1])) {
                        $text2 .= '、' . $type_texts . ';';
                    } elseif (!empty($text2)) {
                        $text2 .= '、' . $type_texts;
                    } elseif (empty($text2) && count($carmodel) == 1) {
                        $text2 .= $type_texts . ';';
                    } else {
                        $text2 .= $type_texts;
                    }
                }
                $lists['text'] = '可用车型:' . $text2 . '适用于:';
                foreach ($typess as $k => $types) {
                    $type_text = config()['config']['type'][$types] ?? '';
                    if (!empty($text) && empty($typess[$k + 1])) {
                        $text .= '、' . $type_text . '。最终是否可抵扣及抵扣金额以支付结果为准，有效期至:' . $lists['endtime'];
                    } elseif (!empty($text)) {
                        $text .= '、' . $type_text;
                    } elseif (empty($text) && count($typess) == 1) {
                        $text .= $type_text . '。最终是否可抵扣及抵扣金额以支付结果为准，有效期至:' . $lists['endtime'];
                    } else {
                        $text .= $type_text;
                    }
                }
                $lists['text'] = $lists['text'] . $text;
            }
            if (empty($data['productid'])) {
                $lists['iscan'] = 2;
                if ($lists['types'] == 2 && $lists['number'] <= 0) {
                    unset($list[$k]);
                }
            } else {
                if ($lists['types'] == 2) {
                    unset($list[$k]);
                } else {
                    $lists['iscan'] = 1;
                    if ($lists['type'] == 1) {
                        if ($total >= $lists['getmoney']) {
                            $lists['iscan'] = 2;
                        }
                    }
                    if ($lists['type'] == 2) {
                        if ($total >= $lists['getmoney'] && $lists['agentid'] == $agentid) {
                            $lists['iscan'] = 2;
                        }
                    }
                }
            }
        }
        if (count($list) > 0) {
            $list = array_values($list);
        }
        $this->result($list, 0, '获取成功');
    }

    public function getcount()
    {
        $data = $this->request->get();
        $type = $this->request->get('type/d', 1);
        $total = 0;
        if (!empty($data['productid'])) {
            $data['productid'] = json_decode($data['productid'] ?? '', true);
            if (empty($data['productid'])) {
                $this->result([], 1, '规格数据错误');
            }
            $list = [];
            $products = [];
            $agentid = 0;
            //获取所有次数券
            foreach ($data['productid'] as $spec) {
                if (empty($spec['id'])  || empty($spec['number'])) {
                    continue;
                }
                //判断商品是否下架
                $product = (new Product())->where(['isdel' => 1, 'isshow' => 1, 'id' => $spec['id']])->find();
                if (empty($product)) {
                    continue;
                }
                if ($type == 2) {
                    $product['price'] = $product['price1'];
                }
                if ($type == 3) {
                    $product['price'] = $product['price2'];
                }
                $products[] = [
                    'id' => $product['id'],
                    'price' => $product['price'],
                    'number' => $spec['number'],
                    'type' => $product['type'],
                ];
                $agentid = $product['agentid'];
            }
            $yyopen = (new Agent())->where('id', $agentid)->value('yyopen') ?? 1; //一元洗鞋开关  1关 2开
            $money = 0;
            $sort = array_column($products, 'price');
            array_multisort($sort, SORT_DESC, $products);
            $have = (new Coupon())->where(['types' => 2, 'status' => 1, 'user_id' => $this->request->user_id, 'agentid' => [0, $agentid]])->order(['modelcount' => 'asc', 'endtime' => 'asc'])->field('id,types,number,status,productid,system,getmoney,carmodel')->select();
            foreach ($products as $product) {
                foreach ($have as $coupon) {
                    if ($yyopen == 1 &&  ($coupon['system'] == 3 || $coupon['system'] == 4)) {
                        continue;
                    }
                    $typess = explode(',', $coupon['productid']);
                    $carmodels = explode(',', $coupon['carmodel']);
                    if ($coupon['status'] == 1 && $product['number'] > 0 && in_array($product['type'], $typess) && in_array($type, $carmodels)) {
                        $number = 1;
                        $product['number'] = $product['number'] - $number;
                        $coupon['status'] = 2;
                        if ($number > 0) {
                            $numbers = empty($list[$product['id']]['dnumber']) ? 0 : (int)$list[$product['id']]['dnumber'];
                            $list[$product['id']] = [
                                'id' => $product['id'],
                                'dnumber' => $number + $numbers
                            ];
                            if ($coupon['system'] == 3 || $coupon['system'] == 4) {
                                $money += round($coupon['getmoney'], 2);
                                if ($product['type'] == 2) {
                                    $money += 10;
                                }
                            }
                        }
                        $total += $number * $product['price'];
                    }
                }
            }
        }
        $total = round($total, 2);
        if ($total >= $money && $money > 0) {
            $total = round(($total - $money), 2);
        }
        $arr = [];
        $arr['total'] = $total;
        $arr['colose'] = 2;
        $arr['list'] = array_values($list);
        $this->result($arr, 0, '获取成功');
    }


    public function putorder()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'productid' => 'require',
            'carid' => 'require',
            'appointment' => 'require',
            'getaddress' => 'require',
            'address' => 'require',
            'street' => 'require',
            'lat' => 'require',
            'lon' => 'require',
        ], [
            'productid.require' => '产品ID不能为空',
            'carid.require' => '地址信息不能为空',
            'appointment.require' => '预约时间不能为空',
            'getaddress.require' => '定位地址信息不能为空',
            'address.require' => '车辆位置不能为空',
            'street.require' => '街道信息不能为空',
            'lat.require' => '坐标不能为空',
            'lon.require' => '坐标不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $startime = date('Y-m-d H:i:s', strtotime(date('Y-m-d', time())));
        $endtime = date('Y-m-d H:i:s');
        $ordered = (new Order())->whereBetweenTime('created', $startime, $endtime)
            ->where(['status' => [1, 2, 3, 4], 'user_id' => $this->request->user_id])->count();
        if ($ordered >= 1) {
            $this->result([], 1, '每用户一天仅可下一单,请先完成未支付订单或明日再下单');
        }
        if (!empty($data['payment']) && $data['payment'] == 1) {
            $this->result([], 1, '线下支付通道已关闭');
        }
        // if (!empty($data['payment']) && $data['payment'] == 3) {
        //     $this->result([], 1, '抖音支付暂未开放，目前仅支持线下支付');
        // }
        Log::write($data, 'test');
        if (!is_array($data['productid'])) {
            $data['productid'] = json_decode($data['productid'], true) ?? [];
        }
        if (empty($data['productid']) || !is_array($data['productid'])) {
            $this->result([], 1, '产品数据错误');
        }
        //查询车辆信息是否存在
        $car = (new Car())->where(['user_id' => $this->request->user_id, 'id' => $data['carid']])->find();
        if (empty($car)) {
            $this->result([], 1, '车辆信息不存在');
        }
        //判断当前区域是否有代理
        $address = getlatlon($data['lat'], $data['lon'], 3);
        if (empty($address['agentid'])) {
            $address = getdrees($data['street'], 3);
        }
        $agentid = $address['agentid'] ?? 0;
        if (empty($agentid)) {
            $this->result([], 1, '当前区域未开通');
        }
        //查一下是否全国代理
        $isall = (new AgentArea())->where(['agentid' => $agentid])->find();
        if (!empty($isall) && $isall['type'] == 1) {
            $this->result([], 1, '当前区域暂未开通');
        }
        //查询是否有街道服务人员
        // if ($isall['type'] == 5) {
        $RiderStreet = (new RiderStreet())->where(['status' => 2, 'agentid' => $agentid])->column('riderid');
        // } else {
        //     $RiderStreet = (new RiderStreet())->where(['street' => $data['street'], 'status' => 2, 'agentid' => $agentid])->column('riderid');
        // }
        if (count($RiderStreet) <= 0) {
            $this->result([], 1, '当前地址区域没有服务人员');
        }
        $RiderList = (new RiderList())->where(['id' => $RiderStreet, 'status' => 1])->column('id');
        if (count($RiderList) <= 0) {
            $this->result([], 1, '当前地区服务人员繁忙，请稍后再下单');
        }
        $order = [
            'user_id' => $this->request->user_id,
            'ordersn' => reordersn(new Order()),
            'agentid' => $agentid ?? 0,
            'name' => $car['name'],
            'mobile' => $car['mobile'],
            'province' => $address['province'],
            'city' => $address['city'],
            'area' => $address['area'],
            'street' => $data['street'],
            'posaddress' => $data['getaddress'],
            'address' => $data['address'],
            'lat' => $data['lat'],
            'lon' => $data['lon'],
            'appointment' => $data['appointment'],
            'info' => $data['info'] ?? '',
            'cardstype' => $car['type'],
            'keyss' => $data['keyss'] ?? '',
            'cards' => $car['cards'],
            'model' => $car['model'],
            'color' => $car['color'],
            'status' => 1,
            'coupon' => !empty($data['coupon']) ? $data['coupon'] : 0,
            'coupons' => '',
            'cmoneys' => 0,
            'endmoney' => 0,
            'cmoney' => 0,
            'dict' => 0,
            'isfirst' => 0,
            'ptotal' => 0,
            'ccount' => 0,
            'dicttotal' => 0,
            'total' => 0,
        ];
        $orderproduct = [];
        //优惠券减免
        $ccount = [];
        foreach ($data['productid'] as $product) {
            if (empty($product['id'])  || empty($product['number'])) {
                $this->result([], 1, '产品参数错误');
            }
            //查询规格是否存在
            $products = (new Product())->where(['isdel' => 1, 'isshow' => 1, 'id' => $product['id']])->find();
            if (empty($products)) {
                $this->result([], 1, '产品已下架,请刷新页面重新提交订单');
            }
            if (empty($order['agentid'])) {
                $order['agentid'] = $agentid;
            }
            if ($car['model'] == 2) {
                $products['price'] = $products['price1'];
            }
            if ($car['model'] == 3) {
                $products['price'] = $products['price2'];
            }
            //查找下面有没有相关服务人员
            $orderproduct[] = [
                'ordersn' => $order['ordersn'],
                'agentid' => $agentid ?? 0,
                'cate' => $products['cate'],
                'productid' => $products['id'],
                'title' =>  $products['title'],
                'descs' =>  !empty($products['descs']) ? $products['descs'] : '无',
                'images' =>  $products['images'],
                'price' =>  $products['price'],
                'number' =>  $product['number'],
                'numbers' =>  $product['number'],
                'type' => $products['type'],
                'cnumber' => 0,
                'cid' => ''
            ];
            $order['ptotal'] += $product['number'] * $products['price'];
        }
        if ($agentid != $order['agentid']) {
            $this->result([], 1, '位置发送变化，请重新选择服务项目');
        }
        //进行排序减免券
        $list = [];
        $sort = array_column($orderproduct, 'price');
        array_multisort($sort, SORT_DESC, $orderproduct);
        $porderm = 0; //一元抵扣券
        $agent = (new Agent())->where('id', $agentid)->find(); //一元洗鞋开关  1关 2开
        //查询时间段订单量
        if (!empty($agent['truecount']) && $agent['truecount'] == 2) {
            //查询时间段订单量
            $timeorder = (new Order())->where(['agentid' => $agentid, 'status' => [2, 3], 'appointment' => $data['appointment']])->count();
            //查询师傅人数
            if (count($RiderList) <= $timeorder) {
                $this->result([], 1, '当前预约时间段无师傅人员,请更改预约时间段');
            }
        }
        $yyopen = $agent['yyopen'] ?? 1;
        //查找可用券
        $have = (new Coupon())->where(['types' => 2, 'status' => 1, 'user_id' => $this->request->user_id, 'agentid' => [0, $agentid]])->order(['modelcount' => 'asc', 'endtime' => 'asc'])->field('id,types,number,status,productid,btmoney,system,getmoney,carmodel')->select();
        foreach ($orderproduct as &$oproduct) {
            foreach ($have as $coupons) {
                if ($yyopen == 1 &&  ($coupons['system'] == 3 || $coupons['system'] == 4)) {
                    continue;
                }
                $typess = explode(',', $coupons['productid']);
                $carmodels = explode(',', $coupons['carmodel']);
                if ($coupons['status'] == 1 && $oproduct['numbers'] > 0 && in_array($oproduct['type'], $typess) && in_array($order['model'], $carmodels)) {
                    $number = 1;
                    $oproduct['numbers'] = $oproduct['numbers'] - $number;
                    $coupons['status'] = 2;
                    if ($number > 0) {
                        $numbers = empty($list[$oproduct['productid']]['dnumber']) ? 0 : (int)$list[$oproduct['productid']]['dnumber'];
                        $cid =  empty($list[$oproduct['productid']]['cid']) ? $coupons['id'] : $list[$oproduct['productid']]['cid'] . ',' . $coupons['id'];
                        $list[$oproduct['productid']] = [
                            'id' => $oproduct['productid'],
                            'dnumber' => $number + $numbers,
                            'cid' => $cid
                        ];
                        $ccount[] = $coupons['id'];
                        $oproduct['cnumber'] = $list[$oproduct['productid']]['dnumber'] ?? 0;
                        $oproduct['cid'] = $cid ?? 0;
                        if ($coupons['system'] == 3 || $coupons['system'] == 4) {
                            $porderm += $coupons['getmoney'];
                            if ($oproduct['type'] == 2) {
                                $porderm += 10;
                            }
                        }
                    }
                    $order['cmoneys'] +=  $number * $coupons['btmoney'];
                    $order['ccount'] += $number * $oproduct['price'];
                }
            }
        }
        if ($order['ccount'] >= $porderm && $porderm > 0) {
            $order['ccount'] = $order['ccount'] - $porderm;
            $order['isfirst'] = $porderm;
        }
        $ymoney = 0; //优惠券减免
        if (!empty($data['coupon'])) {
            $coupon = (new Coupon())->where(['id' => $data['coupon'], 'user_id' => $this->request->user_id, 'status' => 1, 'types' => 1])->find();
            if (empty($coupon)) {
                $this->result([], 1, '优惠券不存在或已使用');
            }
            if ($coupon['type'] == 2 && $coupon['agentid'] != $order['agentid']) {
                $this->result([], 1, '优惠券在该区域平台不可用');
            }
            if ($coupon['getmoney'] > $order['ptotal']) {
                $this->result([], 1, '优惠券未达到使用条件');
            }
            if ($coupon['money'] > $order['ptotal']) {
                $order['cmoney'] = $order['ptotal'];
                $ymoney = $coupon['money'];
            } else {
                $order['cmoney'] = $coupon['money'];
                $order['total'] -= $coupon['money'];
                $ymoney = $coupon['money'];
            }
        }
        $order['total'] = $order['ptotal'] - $order['ccount'] - $ymoney;
        $order['coupons'] = json_encode($ccount, true);
        $order['endmoney'] = $order['total'] + $order['cmoneys'];
        if ($order['total'] <= 0) {
            $order['payment'] = 1;
            $order['total'] = 0;
            $order['status'] = 2;
        }
        Db::startTrans();
        try {
            (new Order())->save($order);
            (new OrderProduct())->allowfield(true)->saveAll($orderproduct);
            if (!empty($data['cartid'])) {
                (new Cart())->where(['id' => $data['cartid'], 'user_id' => $this->request->user_id])->delete();
            }
            if (!empty($coupon)) {
                (new Coupon())->where(['id' => $coupon['id'], 'user_id' => $this->request->user_id, 'status' => 1])->update(['status' => 3]);
            }
            if (count($ccount) > 0) {
                foreach ($ccount as $counts) {
                    (new Coupon())->where(['id' => $counts])->update(['status' => 2]);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, $e->getMessage());
        }
        if ($order['status'] == 1) {
            $text = '下单成功,请在线支付订单';
        } else {
            $text = '下单成功';
        }
        $this->result(['ordersn' => $order['ordersn'], 'status' => $order['status']], 0, $text);
    }

    public function keylog()
    {
        $list = (new Pkey())->field('ltime as updated,type,status,promoid,agentid')->where(['user_id' => $this->request->user_id])->order('ltime desc')->select();
        foreach ($list as $lists) {
            $promo = (new Promo())->where('id', $lists['promoid'])->value('title') ?? '申请套餐';
            if ($lists['type'] == 1) {
                $lists['text'] = '兑换码:' . $lists['code'] . ';兑换码领卡';
                $lists['text'] = $lists['text'] . '(领卡成功)';
            } else {
                $lists['text'] = $promo;
                $title = (new Agent())->where('id', $lists['agentid'])->value('title') ?? '';
                if (!empty($title)) {
                    $lists['text'] = $lists['text'] . '[' . $title . ']';
                }
                if ($lists['status'] == 1) {
                    $lists['text'] = $lists['text'] . '(待审核)';
                }
                if ($lists['status'] == 2) {
                    $lists['text'] = $lists['text'] . '(已发放)';
                }
                if ($lists['status'] == 3) {
                    $lists['text'] = $lists['text'] . '(驳回申请)';
                }
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function info()
    {
        $user = $this->request->user;
        $result = [
            'id' => $user['id'],
            'code' => $user['code'],
            'nickName' => $user['nickName'],
            'avatarUrl' => $user['avatarUrl'],
            'mobile' => $user['mobile'],
            'money' => $user['money'],
            'integral' => $user['integral'],
            'integralall' => $user['integralall'],
        ];
        $this->result($result, 0, '获取成功');
    }

    public function integrallog()
    {
        $type = $this->request->get('type/d', 1);
        if ($type == 2) {
            $model = new MoneyLog();
        } else {
            $model = new IntergralLog();
        }
        $list = $model
            ->where('user_id', $this->request->user_id)
            ->field('created,info,money')
            ->order('id desc')
            ->paginate(20, false, ['query' => $this->request->param()]);
        $this->result($list, 0, '获取成功');
    }

    public function orderstatus()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'ordersn' => 'require',
            'status' => 'require|in:2,4,5'
        ], [
            'ordersn.require' => '订单编号不能为空',
            'status.require' => '状态不能为空',
            'status.in' => '状态不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Order())->where('ordersn', $data['ordersn'])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        switch ($data['status']) {
            case '2':
                if ($order['status'] != 1) {
                    $this->result([], 1, '订单不处于支付状态');
                }
                if (empty($data['payment'])) {
                    $this->result([], 1, '订单支付方式错误');
                }
                if ($data['payment'] == 1) {
                    if ($this->request->user['type'] == 1) {
                        $this->result([], 1, '线下支付通道已关闭，请选择在线支付');
                    }
                    //支付订单
                    Db::startTrans();
                    try {
                        (new Order())->where('id', $order['id'])->update(['status' => $data['status'], 'paytime' => date('Y-m-d H:i:s'), 'payment' => $data['payment']]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                } elseif ($data['payment'] == 2) {
                    //支付订单 返回微信信息
                    $ordersn = repayorder(new Payment());
                    $wechatarr = [
                        'pay_title' => '项目订单，编号' . $order['ordersn'],
                        'payment_id' =>  $ordersn,
                        'money' => $order['total'],
                        'ip' => $this->request->ip(),
                        'user_id' => $this->request->user_id,
                        'params' => json_encode(['trade_type' => 'JSAPI'], true)
                    ];
                    $list = (new Wechat())->pay($wechatarr);
                    if ($list['status'] == true) {
                        //存储支付订单记录
                        $res = (new Payment())->save(['user_id' => $this->request->user_id, 'money' => $order['total'], 'type' => 1, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $order['ordersn']]);
                        if ($res) {
                            $this->result($list, 0, '获取成功');
                        } else {
                            $this->result([], 1, '获取失败,请重试');
                        }
                    } else {
                        $this->result([], 1, $list['msg'] ?? '获取失败');
                    }
                } elseif ($data['payment'] == 3) {
                    //支付订单 返回微信信息
                    $ordersn = repayorder(new Payment());
                    $wechatarr = [
                        'pay_title' => '项目订单，编号' . $order['ordersn'],
                        'payment_id' =>  $ordersn,
                        'money' => $order['total'],
                        'ip' => $this->request->ip(),
                        'user_id' => $this->request->user_id,
                        'params' => json_encode(['trade_type' => 'JSAPI'], true)
                    ];
                    $list = (new Douyin())->pay($wechatarr);
                    if ($list['status'] == true) {
                        //存储支付订单记录
                        $res = (new Payment())->save(['user_id' => $this->request->user_id, 'paytype' => 2, 'money' => $order['total'], 'type' => 1, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $order['ordersn']]);
                        if ($res) {
                            $this->result($list, 0, '获取成功');
                        } else {
                            $this->result([], 1, '获取失败,请重试');
                        }
                    } else {
                        $this->result([], 1, $list['msg'] ?? '获取失败');
                    }
                } elseif ($data['payment'] == 4) {
                    //判断余额是否足够
                    if ($this->request->user['money'] < $order['total']) {
                        $this->result([], 1, $list['msg'] ?? '余额不足');
                    }
                    $user = $this->request->user;
                    Db::startTrans();
                    try {
                        (new Order())->where('id', $order['id'])->update(['status' => $data['status'], 'paytime' => date('Y-m-d H:i:s'), 'payment' => $data['payment']]);
                        (new Users())->MondyEdit($user['id'], $user['money'], -$order['total'], 2, 0, '支付订单');
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                }
                break;
            case '4':
                if ($order['status'] != 3) {
                    $this->result([], 1, '订单状态不可完成');
                }
                //完成订单
                $user = $this->request->user;
                Db::startTrans();
                try {
                    (new Order())->where('id', $order['id'])->update(['status' => $data['status'], 'endtime' => date('Y-m-d H:i:s')]);
                    (new Users())->IntergralEdit($user['id'], $user['integral'], $order['total'], 1, $order['id'], '下单赠送');
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->result([], 1, $e->getMessage());
                }
                $this->result([], 0, '操作成功');
                break;
            case '5':
                $msg = '取消成功';
                if ($order['status'] != 1 && $order['status'] != 2) {
                    $this->result([], 1, '订单状态不可取消');
                }
                //取消
                $data['refund'] = $order['refund'];
                if ($order['status'] == 2 && $order['total'] > 0 && $order['payment'] > 1) {
                    $data['refund'] = 2;
                    $msg = "取消成功，退款稍后原路返回";
                }
                $coupon = json_decode($order['coupons'], true) ?? [];
                Db::startTrans();
                try {
                    if ($order['coupon'] > 0) {
                        (new Coupon())->where('id', $order['coupon'])->update(['status' => 1]);
                    }
                    (new Order())->where('id', $order['id'])->update([
                        'status' => $data['status'],
                        'caceltime' => date('Y-m-d H:i:s'),
                        'refund' => $data['refund']
                    ]);
                    if (count($coupon) > 0) {
                        (new Coupon())->where(['id' => $coupon])->update(['status' => 1]);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->result([], 1, $e->getMessage());
                }
                $this->result([], 0, $msg);
                break;
            default:
                $this->result([], 1, '状态出错');
                break;
        }
    }

    public function recharge()
    {
        if ($this->request->isPost()) {

            $data = $this->request->post();
            $validate = new Validate([
                'money' => 'require|gt:0',
                'payment' => 'require|in:2,3'
            ], [
                'money.require' => '充值金额不能为空',
                'money.gt' => '充值金额必须大于0',
                'payment.require' => '支付方式不能为空',
                'payment.in' => '支付方式不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $this->result([], 1, '充值通道暂未开放');
            //支付订单 返回微信信息
            $ordersn = repayorder(new Payment());
            $wechatarr = [
                'pay_title' => '充值余额支付订单',
                'payment_id' =>  $ordersn,
                'money' => $data['money'],
                'ip' => $this->request->ip(),
                'user_id' => $this->request->user_id,
                'params' => json_encode(['trade_type' => 'JSAPI'], true)
            ];
            if (empty($data['payment']) || $data['payment'] == 2) {
                $list = (new Wechat())->pay($wechatarr);
                if ($list['status'] == true) {
                    //存储支付订单记录
                    $res = (new Payment())->save(['user_id' => $this->request->user_id, 'money' => $data['money'], 'type' => 4, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $this->request->user_id, 'paytype' => 1]);
                    if ($res) {
                        $this->result($list, 0, '获取成功');
                    } else {
                        $this->result([], 1, '获取失败,请重试');
                    }
                } else {
                    $this->result([], 1, $list['msg'] ?? '获取失败');
                }
            } elseif ($data['payment'] == 3) {
                $list = (new Douyin())->pay($wechatarr);
                if ($list['status'] == true) {
                    //存储支付订单记录
                    $res = (new Payment())->save(['user_id' => $this->request->user_id, 'money' => $data['money'], 'type' => 4, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $this->request->user_id, 'paytype' => 2]);
                    if ($res) {
                        $this->result($list, 0, '获取成功');
                    } else {
                        $this->result([], 1, '获取失败,请重试');
                    }
                } else {
                    $this->result([], 1, $list['msg'] ?? '获取失败');
                }
            }
            $this->result([], 1, $list['msg'] ?? '获取失败');
        } else {
            $list = [
                ['money' => 50, 'getmoney' => 50],
                ['money' => 100, 'getmoney' => 100],
                ['money' => 200, 'getmoney' => 200],
                ['money' => 500, 'getmoney' => 500],
                ['money' => 1000, 'getmoney' => 1000],
                ['money' => 2000, 'getmoney' => 2000],
            ];
            $this->result($list, 0, '获取成功');
        }
    }

    public function buy_comobo()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require|gt:0'
        ], [
            'id.require' => '套餐ID不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        //查询套餐是否存在
        $promo = (new Promo())->where(['status' => 1, 'type' => 2, 'id' => $data['id']])->find();
        if (empty($promo)) {
            $this->result([], 1, '套餐不存在');
        }
        $promo['coupon'] = json_decode($promo['coupon'], true) ?? [];
        if (empty($promo['coupon']) || count($promo['coupon']) <= 0) {
            $this->result([], 1, '套餐已关闭');
        }
        //支付订单 返回微信信息
        $ordersn = repayorder(new Payment());
        $wechatarr = [
            'pay_title' => '购买套餐支付订单',
            'payment_id' =>  $ordersn,
            'money' => $promo['money'],
            'ip' => $this->request->ip(),
            'user_id' => $this->request->user_id,
            'params' => json_encode(['trade_type' => 'JSAPI'], true)
        ];
        $parmes = json_encode(['user_id' => $this->request->user_id], true);
        if (empty($data['payment']) || $data['payment'] == 2) {
            $list = (new Wechat())->pay($wechatarr);
            if ($list['status'] == true) {
                //存储支付订单记录
                $res = (new Payment())->save(['user_id' => $this->request->user_id, 'parmes' => $parmes, 'money' => $promo['money'], 'type' => 5, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $promo['id'], 'paytype' => 1]);
                if ($res) {
                    $this->result($list, 0, '获取成功');
                } else {
                    $this->result([], 1, '获取失败,请重试');
                }
            } else {
                $this->result([], 1, $list['msg'] ?? '获取失败');
            }
        } elseif ($data['payment'] == 3) {
            $list = (new Douyin())->pay($wechatarr);
            if ($list['status'] == true) {
                //存储支付订单记录
                $res = (new Payment())->save(['user_id' => $this->request->user_id, 'parmes' => $parmes, 'money' => $promo['money'], 'type' => 5, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $promo['id'], 'paytype' => 2]);
                if ($res) {
                    $this->result($list, 0, '获取成功');
                } else {
                    $this->result([], 1, '获取失败,请重试');
                }
            } else {
                $this->result([], 1, $list['msg'] ?? '获取失败');
            }
        }
        $this->result([], 1, $list['msg'] ?? '获取失败');
    }

    public function orderlist()
    {
        if (empty($this->request->user_id)) {
            $this->result([], 0, '获取成功');
        }
        $status = $this->request->get('status/d', '');
        $list = (new Order())->order('id desc');
        if (!empty($status)) {
            $list = $list->where('status', $status);
        }
        $list = $list->where('user_id', $this->request->user_id)->field('id,ordersn,ispj,status,ptotal,total,refund,created,cards,name,mobile,color,model,info,appointment,address,posaddress,street')->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['tnumber'] = 0;
            $ordergoods = (new OrderProduct())->field('title,descs,price,number,cnumber,images')->where(['ordersn' => $lists['ordersn']])->select();
            foreach ($ordergoods as $goods) {
                $lists['tnumber'] += $goods['number'];
            }
            $lists['goods'] = $ordergoods;
            $lists['status_text'] = $lists->status_text;
            $lists['model_text'] = $lists->model_text;
            $address = getdrees($lists['street'], 2);
            $lists['area_text'] = $address['area'];
            $lists['street_text'] = $address['street'];
        }
        $this->result($list, 0, '获取成功');
    }


    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Order())->where('id', $id)->field('id,payment,agentid,ccount,ispj,ordersn,ptotal,cmoney,total,appointment,created,info,status,street,cards,name,mobile,color,model,keyss,posaddress,address,orderid,refund,images1,images2')->find();
        if ($list) {
            $list['sendmoney'] = 0; //配送费
            $list['status_text'] = $list->status_text;
            $list['payment_text'] = $list->payment_text;
            $address = getdrees($list['street'], 2);
            $list['province_text'] = $address['province'];
            $list['city_text'] = $address['city'];
            $list['area_text'] = $address['area'];
            $list['street_text'] = $address['street'];
            $list['model_text'] = $list->model_text;
            $goods = (new OrderProduct())->where('ordersn', $list['ordersn'])->field('images,number,descs,title,price,cnumber')->select();
            $list['good'] = $goods;
            $list['ridername'] = '';
            $list['ridermobile'] = '';
            if ($list['orderid'] > 0) {
                $rider = (new Riderlist())->where('id', $list['orderid'])->field('name,mobile,riderlat,riderlon')->find();
                $list['ridername'] = $rider['name'] ?? '';
                $list['ridermobile'] = $rider['mobile'] ?? '';
            }
            $images1 = json_decode($list['images1'] ?? '', true) ?? [];
            $images2 = json_decode($list['images2'] ?? '', true) ?? [];
            $list['images1'] = [];
            $list['images2'] = [];
            $list['tsmobile'] = (new Agent())->where('id', $list['agentid'])->value('mobile') ?? '';
            if (is_array($images1)) {
                $list['images1'] = $images1;
            }
            if (is_array($images2)) {
                $list['images2'] = $images2;
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function  message()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'message' => 'require',
                'type' => 'require|in:1,2,3',
            ], [
                'message.require' => '反馈内容为空',
                'type.require' => '反馈类型不能为空',
                'type.in' => '反馈类型不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $data['messtype'] = $data['type'];
            $data['type'] = 1;
            $data['user_id'] = $this->request->user_id;
            if (!empty($data['images'])) {
                $images = json_decode($data['images'] ?? '', true) ?? [];
                if (is_array($images) && count($images) > 0) {
                    $data['images'] = json_encode($images, true);
                } else {
                    $data['images'] = '';
                }
            } else {
                $data['images'] = '';
            }
            $res = (new Message())->allowfield(true)->save($data);
            if ($res) {
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败');
        } else {
            $list = (new Message())->order('id desc');
            $list = $list->where(['user_id' =>  $this->request->user_id, 'type' => 1])
                ->field('message,reply,mobile,created,images,messtype')
                ->paginate(20, false, ['query' => $this->request->param()])->each(function ($item) use ($list) {
                    $item['images'] = json_decode($item['images'], true) ?? [];
                    $item['type_text'] = $item->type_text;
                    return $item;
                });
            $this->result($list, 0, '查询完成');
        }
    }

    public function invitlist()
    {
        $list = [
            'people' => 0, //邀请人
            'todaypeople' => 0, //邀请收益
            'list' => [] //邀请列表
        ];
        $list['people'] = [];
        $user = (new Users())->where('pid', $this->request->user_id)->order('id desc')->field('id,nickName,avatarUrl,DATE_FORMAT(created, "%Y-%m-%d" ) as createds')->select();
        foreach ($user as $users) {
            $users['income'] = (new Order())->where(['user_id' => $users['id'], 'status' => 4])->sum('ptotal');
            $list['todaypeople'] += $users['income'];
        }
        $list['todaypeople'] = floor($list['todaypeople'] * 100) / 100;
        $list['people'] = count($user);
        $list['list'] = $user;
        $this->result($list, 0, '查询完成');
    }

    public function invitlog()
    {
        $users = (new Users())->where('pid', $this->request->user_id)->column('id');
        $lists = (new Order())->where(['user_id' => $users, 'status' => 4])->field('created,ptotal as total,ordersn')->order('id desc')
            ->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($lists as $list) {
            $list['info'] = '订单编号:' . $list['ordersn'];
        }
        $this->result($lists, 0, '查询完成');
    }


    public function riderapply()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'mobile' => 'require',
                'password' => 'require',
                'name' => 'require',
                'cards' => 'require',
                'positive' => 'require',
                'negative' => 'require',
                'street' => 'require'
            ], [
                'mobile.require' => '手机号不能为空',
                'password.require' => '密码不能为空',
                'name.require' => '名称不能为空',
                'cards.require' => '身份证号不能为空',
                'positive.require' => '身份证正面不能为空',
                'negative.require' => '身份证反面不能为空',
                'street.require' => '街道ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
                $this->result([], 1, '联系电话格式不正确');
            }
            $data['password'] = md5(md5($data['password']));
            $data['lat'] = $data['lat'] ?? 0;
            $data['lng'] = $data['lng'] ?? 0;
            $streets = getlatlon($data['lat'], $data['lng'], 3);
            if (empty($streets['street'])) {
                $streets = getdrees($data['street'], 3);
            }
            if (empty($streets['street']) || empty($streets['area']) || empty($streets['city']) || empty($streets['province'])) {
                $this->result([], 1, '地址信息错误，请重新选择或刷新页面重试');
            }
            //代理ID
            if (empty($streets['agentid'])) {
                $this->result([], 1, '当前位置暂未开放申请');
            }
            $data['street'] = $streets['street'];
            //查一下是否全国代理
            $isall = (new AgentArea())->where(['type' => 1, 'agentid' => $streets['agentid']])->find();
            if (!empty($isall)) {
                $this->result([], 1, '当前位置不支持申请');
            }
            $save = [
                'user_id' => $this->request->user_id,
                'mobile' => $data['mobile'],
                'password' => $data['password'],
                'name' => $data['name'],
                'cards' => $data['cards'],
                'positive' => $data['positive'],
                'negative' => $data['negative'],
            ];
            $rider = (new RiderList())->where(['mobile' => $data['mobile']])->find();
            $riderid = 0;
            if (!empty($rider)) {
                $riderid = $rider['id'] ?? 0;
                if ($rider['user_id'] != $this->request->user_id) {
                    $this->result([], 1, '该账号已被其它微信账号绑定,非当前微信可操作');
                }
            }
            //查到师傅id 再查看街道信息是否已经存在
            if (!empty($riderid)) {
                $riderstreet = (new RiderStreet())->where(['riderid' => $riderid])->find();
                if (!empty($riderstreet) && $riderstreet['status'] == 1) {
                    $this->result([], 1, '当前街道已在审核中，请登陆账号街道管理内查看');
                }
                if (!empty($riderstreet) && $riderstreet['status'] == 2) {
                    $this->result([], 1, '您已通过，请登陆账号街道管理内查看');
                }
            }
            //保存数据
            $addstreet = [
                'riderid' => $riderid,
                'agentid' => $streets['agentid'] ?? 0,
                'province' => $streets['province'],
                'city' => $streets['city'],
                'area' => $streets['area'],
                'street' => $streets['street'],
                'status' => 1,
                'lat' => $data['lat'],
                'lon' => $data['lng']
            ];
            Db::startTrans();
            try {
                //如果有师傅信息就更新 没有就保存
                if (!empty($rider)) {
                    (new RiderList())->allowfield(true)->save($save, ['id' => $rider['id']]);
                } else {
                    $riderid = (new RiderList())->insertGetId($save);
                }
                $addstreet['riderid'] = $riderid;
                //查询街道有没有就提交 已有就更新
                if (empty($riderstreet)) {
                    (new RiderStreet())->allowfield(true)->save($addstreet);
                } else {
                    (new RiderStreet())->allowfield(true)->save($addstreet, ['id' => $riderstreet['id']]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '提交失败，请重试');
            }
            $this->result([], 0, '申请成功,您可登陆账号查看审核状态');
        } else {
            $list = (new RiderList())->field('user_id,password', true)->where(['user_id' => $this->request->user_id])->find();
            if (!empty($list)) {
                $riderstreet = (new RiderStreet())->where(['riderid' => $list['id']])->find();
                if (!empty($riderstreet)) {
                    $list['province'] = $riderstreet['province'];
                    $list['city'] = $riderstreet['city'];
                    $list['area'] = $riderstreet['area'];
                    $list['street'] = $riderstreet['street'];
                    $list['province_text'] = (new Region())->where(['area_code' => $riderstreet['province']])->value('name');
                    $list['city_text'] = (new Region())->where(['area_code' => $riderstreet['city']])->value('name');
                    $list['area_text'] = (new Region())->where(['area_code' => $riderstreet['area']])->value('name');
                    $list['street_text'] = (new Region())->where(['id' => $riderstreet['street']])->value('name');
                    $list['status'] = $riderstreet['status'];
                }
            }
            $this->result($list, 0, '获取成功');
        }
    }

    public function promo()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'rider' => 'require',
                'agentid' => 'require|gt:0'
            ], [
                'id.require' => 'ID不能为空',
                'rider.require' =>  '师傅ID不能为空',
                'agentid.require' => '区域ID不能为空',
                'agentid.gt' => '代理ID必须大于0'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $promo = (new Promo())->where(['id' => $data['id'], 'agentid' => $data['agentid']])->find();
            if (empty($promo)) {
                $this->result([], 1, '获取套餐信息失败');
            }
            if ($promo['status'] != 1) {
                $this->result([], 1, '活动已结束');
            }
            //是否已提交申请，不能重复提交
            $have = (new Pkey())->where(['promoid' => $promo['id'], 'status' => 1, 'type' => 2, 'user_id' => $this->request->user_id])->find();
            if (!empty($have)) {
                $this->result([], 1, '您已提交申请，无需重复提交');
            }
            Db::startTrans();
            try {
                $code = rekey(new Pkey(), '');
                (new Pkey())->allowfield(true)->save([
                    'promoid' => $promo['id'],
                    'status' => 1,
                    'type' => 2,
                    'user_id' => $this->request->user_id,
                    'code' => $code,
                    'rider' => $data['rider'],
                    'agentid' => $promo['agentid'],
                    'money' => $promo['money']
                ]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, $e->getMessage());
            }
            $this->result([], 0, '申请成功，请联系工作人员审核');
        } else {
            $this->result([], 0, '获取成功');
        }
    }
}
